package itsm.isperp.report.resolver;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.report.Counter;
import itsm.isperp.report.analyzer.SortAnalyzer;
import itsm.isperp.report.data.warehouse.QueryRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 
 * 有解析器输出最终数据
 * 
 * 
 * @author lizx
 * @date 2015-8-25
 * @since 1.0
 * 
 */
public class DataResolverUtils {

	public static Map<String, Map<String, Counter>> resolve(QueryRequest req) {

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		Map<String, Map<String, Counter>> map = new HashMap<>();

		String sql = req.getSql();

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		Object v = null;
		String kk = null;
		List<String> columns = req.getColumns();
		if (list.size() == 0) {
			return map;
		}

		for (String k : columns) {
			Map<String, Counter> m = new HashMap<>();
			map.put(k, m);
		}

		for (Map<String, Object> icd : list) {

			for (String k : columns) {
				Map<String, Counter> m = map.get(k);

				v = icd.get(k);
				if (v == null) {
					kk = Counter.LABEL_NULL;
					Counter i = m.get(kk);

					if (i == null) {
						m.put(kk, new Counter(kk, 1, 1000));
					} else {
						i.increase();
					}
				} else {
					kk = v.toString();

					kk = "".equals(kk) ? Counter.LABEL_NULL : kk;
					Counter i = m.get(kk);

					if (i == null) {
						m.put(kk, new Counter(kk));
					} else {
						i.increase();
					}
				}
			}
		}

		// 由多到小进行排序
		for (String k : columns) {
			Map<String, Counter> kv = map.get(k);
			map.put(k, SortAnalyzer.sortMapByCount(kv));
		}

		return map;

	}

}
